//
//  GPSLocationViewController.swift
//  TJJPT
//
//  Created by FENGYL on 2017/7/26.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

import UIKit
import SVProgressHUD

class GPSLocationViewController: UIViewController,BMKMapViewDelegate,BMKGeoCodeSearchDelegate,AMapSearchDelegate {
    
    var baiduMapView:BMKMapView?
    var aMapView:MAMapView?
    let baiduMapSearcher:BMKGeoCodeSearch = BMKGeoCodeSearch.init()
    let aMapSearcher:AMapSearchAPI = AMapSearchAPI()
    
    let gpsLocationViewControllerForAMap = GPSLocationViewControllerForAMap()
    
    var isFullScreen = false
    var isSatellite = false
    var isLocation = false
    var locationButtonAnimationRunning = false
    var isBaseStation = false
    var addCircle = false
    
    let locationButton = UIButton.init()
    
    var lastLocationTime:NSNumber = 0
    
    //定时器
    var timer:Timer?
    
    var cancelTimerDate = Date.init()
    var oneTimerFinish = true
    
    
    @IBOutlet weak var rightButton: UIButton!
    
    
    @IBOutlet weak var mapView: UIView!
    @IBOutlet weak var infoView: UIView!
    
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var gpsLongitudeLabel: UILabel!
    @IBOutlet weak var gpsLatiudeLabel: UILabel!
    @IBOutlet weak var altitudeLabel: UILabel!
    @IBOutlet weak var locationInformationLabel: UILabel!
    @IBOutlet weak var powerLabel: UILabel!
    @IBOutlet weak var speedLabel: UILabel!
    @IBOutlet weak var modeLabel: UILabel!
    @IBOutlet weak var satelliteLabel: UILabel!
    
    @IBOutlet weak var timeInfoLabel: UILabel!
    @IBOutlet weak var gpsLongitudeInfoLabel: UILabel!
    @IBOutlet weak var gpsLatitudeInfoLabel: UILabel!
    @IBOutlet weak var altitudeInfoLabel: UILabel!
    @IBOutlet weak var locationInformationInfoLabel: UILabel!
    @IBOutlet weak var powerInfoLabel: UILabel!
    @IBOutlet weak var speedInfoLabel: UILabel!
    @IBOutlet weak var modeInfoLabel: UILabel!
    @IBOutlet weak var satelliteInfoLabel: UILabel!
    
    
    @IBOutlet weak var gpsLongitudeLayoutConstraint: NSLayoutConstraint!
    @IBOutlet weak var altitudeLayoutConstraint: NSLayoutConstraint!
    
    
    
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpView()
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        baiduMapView?.delegate = self
        
        baiduMapSearcher.delegate = self
        
        aMapSearcher.delegate = self
        
        aMapView?.delegate = gpsLocationViewControllerForAMap
        
        startTimer()
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
        baiduMapView?.delegate = nil
        
        baiduMapSearcher.delegate = nil
        
        aMapSearcher.delegate = nil
        
        aMapView?.delegate = nil
        
        stopTimer()
        
        
    }
    
    deinit {
        stopTimer()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        stopTimer()
        
    }
    
    
    // MARK: - 初始化
    func setUpView() {
        
        // MARK: 标题
        self.title = NSLocalizedString(LOCALIZABLE_STRING_BASE_STATION_LOCATION, comment: "")
        
        
        
        // MARK: 右上显示设备名
        rightButton?.setImage(self.getSelectedDeviceConnectedStatusImage(), for: .normal)
        rightButton?.setTitle(self.getSelectedDeviceDisplayName(), for: .normal)
        
        
        
        // MARK: label的间距调整
        let marginForGpsLongitude = (self.gpsLatiudeLabel.frame.origin.y - self.timeLabel.frame.maxY - self.gpsLongitudeLabel.frame.size.height) / 2
        self.gpsLongitudeLayoutConstraint.constant = marginForGpsLongitude
        
        let marginForAltitude = (self.locationInformationLabel.frame.origin.y - self.gpsLatiudeLabel.frame.maxY - self.altitudeLabel.frame.size.height) / 2
        self.altitudeLayoutConstraint.constant = marginForAltitude
        
        
        
        // MARK: 用哪个地图
        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
            
            baiduMapView = BMKMapView.init(frame: self.mapView.bounds)
            
            //约束弊端,不同机型适配宽高
            baiduMapView?.height = (STATIC_VALUE_SCREEN_HEIGHT - (self.navigationController?.navigationBar.height)! - 20) / 7 * 5
            
            baiduMapView?.width = STATIC_VALUE_SCREEN_WIDTH
            
            baiduMapView?.showMapScaleBar = true
            
            self.mapView.addSubview(baiduMapView!)
            
        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP{
            
            ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
            AMapServices.shared().enableHTTPS = true
            
            ///初始化地图
            aMapView = MAMapView.init(frame: self.mapView.bounds)
            
            //约束弊端,不同机型适配宽高
            aMapView?.height = (STATIC_VALUE_SCREEN_HEIGHT - (self.navigationController?.navigationBar.height)! - 20) / 7 * 5
            
            aMapView?.width = STATIC_VALUE_SCREEN_WIDTH
            
            aMapView?.showsScale = true
            
            ///把地图添加至view
            self.mapView.addSubview(aMapView!)
            
        }
        
        // MARK: 下方信息栏
        self.timeLabel.text = NSLocalizedString(LOCALIZABLE_STRING_TIME, comment: "") + ":"
        
        self.gpsLongitudeLabel.text = NSLocalizedString(LOCALIZABLE_STRING_GPS_LONGITUDE, comment: "") + ":"
        
        self.gpsLatiudeLabel.text = NSLocalizedString(LOCALIZABLE_STRING_GPS_LATITUDE, comment: "") + ":"
        
        self.altitudeLabel.text = NSLocalizedString(LOCALIZABLE_STRING_ALTITUDE, comment: "") + ":"
        
        self.locationInformationLabel.text = NSLocalizedString(LOCALIZABLE_STRING_LOCATION_INFORMATION, comment: "") + ":"
        
        self.powerLabel.text = NSLocalizedString(LOCALIZABLE_STRING_POWER, comment: "") + ":"
        
        self.speedLabel.text = NSLocalizedString(LOCALIZABLE_STRING_SPEED, comment: "") + ":"
        
        self.modeLabel.text = NSLocalizedString(LOCALIZABLE_STRING_MODE, comment: "") + ":"
        
        self.satelliteLabel.text = NSLocalizedString(LOCALIZABLE_STRING_SATELLITE, comment: "") + ":"
        
        
        // MARK: 设置定位按钮
        setUpLocationButton()
        
        
        // MARK: 设置顶部两按钮
        setUpTopButton()
        
        
        // MARK: 刷新最后状态
        refreshLastStatus()
        
        
    }
    
    // MARK: - 刷新最后状态
    func refreshLastStatus() {
        
        NetworkCommand.getLastStatusData(listSerialNumber: nil, id: nil, clientType: nil, tokenPass: nil, success: { (response) in
            
            self.setUpInfoView()
            
            // MARK: 提取lastTrackPoiDataBySnsArray
            if UserModel.userModel.lastTrackPoiDataBySnsArray != nil {
                
                for dict in UserModel.userModel.lastTrackPoiDataBySnsArray! {
                    
                    let last:LastTrackPoiDataBySns = LastTrackPoiDataBySns.mj_object(withKeyValues: dict)
                    
                    if last.SerialNumber == UserModel.userModel.selectedDeviceSerialNumber {
                        
                        self.lastLocationTime = last.GPSTime!
                        
                    }
                    
                }
                
            }
            
            
        }) { (Error) in
            
            
            
        }
        
    }
    
    // MARK: - 设置信息栏
    func setUpInfoView() {
        
        // MARK: 设置是否在线图标
        rightButton?.setImage(self.getSelectedDeviceConnectedStatusImage(), for: .normal)
        
        // MARK: 提取lastTrackPoiDataBySnsArray
        var lastTrackPoiDataBySns:LastTrackPoiDataBySns?
        
        if UserModel.userModel.lastTrackPoiDataBySnsArray != nil {
            
            for dict in UserModel.userModel.lastTrackPoiDataBySnsArray! {
                
                let last:LastTrackPoiDataBySns = LastTrackPoiDataBySns.mj_object(withKeyValues: dict)
                
                if last.SerialNumber == UserModel.userModel.selectedDeviceSerialNumber {
                    
                    lastTrackPoiDataBySns = last
                    
                }
                
            }
            
        }
        
        // MARK: 提取
        var lastStatusData:LastStatusData?
        
        if UserModel.userModel.lastStatusDataArray != nil {
            
            for dict in UserModel.userModel.lastStatusDataArray! {
                
                let last:LastStatusData = LastStatusData.mj_object(withKeyValues: dict)
                
                if last.SerialNumber == UserModel.userModel.selectedDeviceSerialNumber {
                    
                    lastStatusData = last
                    
                }
                
            }
            
        }
        
        if lastTrackPoiDataBySns != nil && lastStatusData != nil{
            
            //纬度
            self.gpsLatitudeInfoLabel.text = "\(lastTrackPoiDataBySns?.Lat ?? NSNumber.init())"
            
            //经度
            self.gpsLongitudeInfoLabel.text = "\(lastTrackPoiDataBySns?.Lng ?? NSNumber.init())"
            
            //海拔
            self.altitudeInfoLabel.text = "\(lastTrackPoiDataBySns?.High ?? NSNumber.init())" + "m"
            
            //卫星
            self.satelliteInfoLabel.text = "\(lastTrackPoiDataBySns?.Sates ?? NSNumber.init())"
            
            //电量
            self.powerInfoLabel.text = "\(lastStatusData?.PowerValue ?? NSNumber.init())" + "%"
            
            //模式
            if lastStatusData?.UpMode == 1 {
                
                self.modeInfoLabel.text = "GPS"
                
                isBaseStation = false
                gpsLocationViewControllerForAMap.isBaseStation = false
                
            }else if lastStatusData?.UpMode == 2{
                
                self.modeInfoLabel.text = "LBS"
                
                isBaseStation = true
                gpsLocationViewControllerForAMap.isBaseStation = true
                
            }else {
                
                self.modeInfoLabel.text = "Not found"
                
                isBaseStation = false
                gpsLocationViewControllerForAMap.isBaseStation = false
                
            }
            
            
            //时间
            var connectedDate:Date?
            if lastStatusData?.ConnTime != nil {
                
                let timeInterval:TimeInterval = TimeInterval.init((lastStatusData?.ConnTime)!)
                
                connectedDate = Date.init(timeIntervalSince1970: timeInterval)
                
            }
            
            if connectedDate != nil {
                
                self.timeInfoLabel.text = NetworkCommand.timestampToString(timestamp: (lastStatusData?.ConnTime)!)
                
                //速度
                if lastTrackPoiDataBySns?.Speed != nil {
                    
                    let marginTime = Date.init().timeIntervalSince(connectedDate!)
                    
                    if marginTime > 300 {
                        
                        self.speedInfoLabel.text = "0km/h"
                        
                    }else {
                        
                        self.speedInfoLabel.text = "\(lastTrackPoiDataBySns?.Speed ?? 0)" + "km/h"
                        
                    }
                    
                }
                
            }
            
            
            
            //地址
            if lastTrackPoiDataBySns?.Address != nil {
                
                // MARK: 提取坐标
                var clLocationCoordinate2D:CLLocationCoordinate2D = CLLocationCoordinate2D.init(latitude: 0, longitude: 0)
                
                if lastTrackPoiDataBySns?.Lat != nil && lastTrackPoiDataBySns?.Lng != nil {
                    
                    clLocationCoordinate2D.latitude = (lastTrackPoiDataBySns?.Lat?.doubleValue)!
                    clLocationCoordinate2D.longitude = (lastTrackPoiDataBySns?.Lng?.doubleValue)!
                    
                }
                
                if (lastTrackPoiDataBySns?.Address?.isEmpty)! {
                    
                    if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
                        
                        self.baiduMapReverseGeoCode(coor: clLocationCoordinate2D)
                        
                        
                    }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
                        
                        self.searchReGeocodeWithCoordinate(coordinate: clLocationCoordinate2D)
                        
                    }
                    
                }else {
                    
                    self.locationInformationInfoLabel.text = lastTrackPoiDataBySns?.Address
                    
                }
                
            }else {
                
                var clLocationCoordinate2D:CLLocationCoordinate2D = CLLocationCoordinate2D.init(latitude: 0, longitude: 0)
                
                if lastTrackPoiDataBySns?.Lat != nil && lastTrackPoiDataBySns?.Lng != nil {
                    
                    clLocationCoordinate2D.latitude = (lastTrackPoiDataBySns?.Lat?.doubleValue)!
                    clLocationCoordinate2D.longitude = (lastTrackPoiDataBySns?.Lng?.doubleValue)!
                    
                }
                
                if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
                    
                    self.baiduMapReverseGeoCode(coor: clLocationCoordinate2D)
                    
                    
                }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
                    
                    self.searchReGeocodeWithCoordinate(coordinate: clLocationCoordinate2D)
                    
                }
                
                
                
            }
            
        }
        
        
        // MARK: 定位
        if lastStatusData?.Lat != nil && lastStatusData?.Lng != nil {
            
            let clLocationCoordinate2D = CLLocationCoordinate2DMake((lastStatusData?.Lat?.doubleValue)!, (lastStatusData?.Lng?.doubleValue)!)
            
            if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
                
                let coordinate = coorForWGS84ToBd09(coor: clLocationCoordinate2D)
                
                let annotation = BMKPointAnnotation.init()
                annotation.coordinate = coordinate
                self.baiduMapView?.addAnnotation(annotation)
                
                self.baiduMapView?.zoomLevel = 20
                self.baiduMapView?.setCenter(coordinate, animated: true)
                
                
                
            }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
                
                let coordinate = AMapCoordinateConvert(clLocationCoordinate2D, .GPS)
                
                let annotation = MAPointAnnotation()
                annotation.coordinate = coordinate
                self.aMapView?.addAnnotation(annotation)
                
                self.aMapView?.setZoomLevel(18, animated: true)
                self.aMapView?.setCenter(coordinate, animated: true)
                
                
            }
            
            
            
            
        }
        
        
        // MARK: 添加圈圈
        if addCircle {
            
            if lastStatusData?.Lat != nil && lastStatusData?.Lng != nil {
                
                let clLocationCoordinate2D = CLLocationCoordinate2DMake((lastStatusData?.Lat?.doubleValue)!, (lastStatusData?.Lng?.doubleValue)!)
                
                if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
                    
                    let coordinate = coorForWGS84ToBd09(coor: clLocationCoordinate2D)
                    
                    let circle = BMKCircle.init(center: coordinate, radius: 500)
                    
                    baiduMapView?.add(circle)
                    
                    
                }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
                    
                    let coordinate = AMapCoordinateConvert(clLocationCoordinate2D, .GPS)
                    
                    let circle: MACircle = MACircle(center: coordinate, radius: 500)
                    
                    aMapView?.add(circle)
                    
                    
                }
                
                
                
                
            }
            
        }
        
        
        
    }
    
    // MARK: - 获取所选设备显示名
    func getSelectedDeviceDisplayName() -> String {
        
        var displayName:String = UserModel.userModel.selectedDeviceSerialNumber 
        
        if (UserModel.userModel.devicesByAccountArray != nil) {
            
            for dict in UserModel.userModel.devicesByAccountArray! {
                
                let devicesByAccount = DevicesByAccount.mj_object(withKeyValues: dict)
                
                if devicesByAccount?.SerialNumber == UserModel.userModel.selectedDeviceSerialNumber {
                    
                    displayName = devicesByAccount?.DisplayName ?? UserModel.userModel.selectedDeviceSerialNumber
                    
                }
                
            }
            
            
        }
        
        
        
        return displayName
        
    }
    
    // MARK: - 获取现在状态的Image
    func getSelectedDeviceConnectedStatusImage() -> UIImage {
        
        var image = #imageLiteral(resourceName: "z_gps_Status_outline")
        
        if (UserModel.userModel.lastStatusDataArray != nil) {
            
            for dict in UserModel.userModel.lastStatusDataArray! {
                
                let lastStatusData:LastStatusData = LastStatusData.mj_object(withKeyValues: dict)
                
                if (lastStatusData.ConnStatus == 1 && lastStatusData.SerialNumber == UserModel.userModel.selectedDeviceSerialNumber) {
                    
                    image = #imageLiteral(resourceName: "z_gps_Status_online")
                    
                }
                
            }
            
        }
        
        return image
        
        
    }
    
    
    
    // MARK: - 设置顶上两个按钮
    func setUpTopButton() {
        
        // MARK: 全屏按钮
        let fullScreenButton = UIButton.init(frame: CGRect.init(x: STATIC_VALUE_SCREEN_WIDTH - 20 - 27, y: 20, width: 27, height: 23))
        
        fullScreenButton.setImage(#imageLiteral(resourceName: "tjj_icon_fulScreen"), for: .normal)
        
        fullScreenButton.addTarget(self, action: #selector(setUpFullScreen), for: .touchUpInside)
        
        
        // MARK: 卫星地图按钮
        let satelliteMapButton = UIButton.init(frame: CGRect.init(x: fullScreenButton.frame.minX - 20 - 27, y: 20, width: 27, height: 23))
        
        satelliteMapButton.setImage(#imageLiteral(resourceName: "tjj_icon_Satellite"), for: .normal)
        
        satelliteMapButton.addTarget(self, action: #selector(setUpSatelliteMap), for: .touchUpInside)
        
        
        // MARK: 定位按钮
        let locationButton = UIButton.init(frame: CGRect.init(x: satelliteMapButton.frame.minX - 20 - 27, y: 20, width: 27, height: 23))
        
        locationButton.setImage(#imageLiteral(resourceName: "tjj_icon_local"), for: .normal)
        
        locationButton.addTarget(self, action: #selector(findLocation), for: .touchUpInside)
        
        
        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
            
            self.baiduMapView?.addSubview(fullScreenButton)
            
            self.baiduMapView?.addSubview(satelliteMapButton)
            
            self.baiduMapView?.addSubview(locationButton)
            
        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
            
            self.aMapView?.addSubview(fullScreenButton)
            
            self.aMapView?.addSubview(satelliteMapButton)
            
            self.aMapView?.addSubview(locationButton)
            
        }
        
    }
    
    // MARK: - 全屏
    func setUpFullScreen() {
        
        let window = UIApplication.shared.keyWindow
        
        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
            
            self.baiduMapView?.removeFromSuperview()
            
            if isFullScreen {
                
                let h = (STATIC_VALUE_SCREEN_HEIGHT - (self.navigationController?.navigationBar.height)! - 20) / 7 * 5
                
                locationButton.frame = CGRect(x: 5, y: h - 56.5, width: 40, height: 46.5)
                
                self.baiduMapView?.frame = self.mapView.bounds
                
                self.mapView.addSubview(self.baiduMapView!)
                
            }else {
                
                let h = STATIC_VALUE_SCREEN_HEIGHT
                
                locationButton.frame = CGRect(x: 5, y: h - 56.5, width: 40, height: 46.5)
                
                self.baiduMapView?.frame = (window?.bounds)!
                
                window?.addSubview(self.baiduMapView!)
                
            }
            
        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
            
            self.aMapView?.removeFromSuperview()
            
            if isFullScreen {
                
                let h = (STATIC_VALUE_SCREEN_HEIGHT - (self.navigationController?.navigationBar.height)! - 20) / 7 * 5
                
                locationButton.frame = CGRect(x: 5, y: h - 56.5, width: 40, height: 46.5)
                
                self.aMapView?.frame = self.mapView.bounds
                
                self.mapView.addSubview(self.aMapView!)
                
            }else {
                
                let h = STATIC_VALUE_SCREEN_HEIGHT
                
                locationButton.frame = CGRect(x: 5, y: h - 56.5, width: 40, height: 46.5)
                
                self.aMapView?.frame = (window?.bounds)!
                
                window?.addSubview(self.aMapView!)
                
                
            }
            
            
        }
        
        isFullScreen = !isFullScreen
        
    }
    
    // MAKR: - 卫星地图
    func setUpSatelliteMap() {
        
        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
            
            if isSatellite {
                
                self.baiduMapView?.mapType = UInt(BMKMapTypeStandard)
                
            }else {
                
                self.baiduMapView?.mapType = UInt(BMKMapTypeSatellite)
                
                
            }
            
        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
            
            if isSatellite {
                
                self.aMapView?.mapType = .standard
                
            }else {
                
                self.aMapView?.mapType = .satellite
                
                
            }
            
        }
        
        isSatellite = !isSatellite
        
    }
    
    // MARK: - 定位
    func findLocation() {
        
        if UserModel.userModel.lastStatusDataArray != nil {
            
            if (UserModel.userModel.lastStatusDataArray?.count)! > 0 {
                
                for dict in UserModel.userModel.lastStatusDataArray! {
                    
                    let last = LastStatusData.mj_object(withKeyValues: dict)
                    
                    if last?.SerialNumber == UserModel.userModel.selectedDeviceSerialNumber {
                        
                        if last?.Lat != nil && last?.Lng != nil {
                            
                            let lastCoor = CLLocationCoordinate2DMake((last?.Lat?.doubleValue)!, (last?.Lng?.doubleValue)!)
                            
                            if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
                                
                                let coordinate = coorForWGS84ToBd09(coor: lastCoor)
                                self.baiduMapView?.zoomLevel = 20
                                self.baiduMapView?.setCenter(coordinate, animated: true)
                                
                                
                            }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
                                
                                let coordinate = AMapCoordinateConvert(lastCoor, .GPS)
                                self.aMapView?.setZoomLevel(18, animated: true)
                                self.aMapView?.setCenter(coordinate, animated: true)
                                
                                
                            }
                            
                            
                        }
                        
                    }
                    
                }
                
            }
            
        }
        
    }
    
    // MARK: - 设置定位按钮
    func setUpLocationButton() {
        
        
        locationButton.setImage(#imageLiteral(resourceName: "z_gps_realTime_RTLS"), for: .normal)
        locationButton.setImage(#imageLiteral(resourceName: "z_gps_realTime_RTLS"), for: .highlighted)
        
        let h = (STATIC_VALUE_SCREEN_HEIGHT - (self.navigationController?.navigationBar.height)! - 20) / 7 * 5
        
        locationButton.frame = CGRect(x: 5, y: h - 56.5, width: 40, height: 46.5)
        
        locationButton.addTarget(self, action: #selector(touchLocationButton), for: .touchUpInside)
        
        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
            
            self.baiduMapView?.addSubview(locationButton)
            
        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
            
            self.aMapView?.addSubview(locationButton)
            
        }
        
        
    }
    
    // MARK: - 点击定位按钮
    func touchLocationButton() {
        
        locationButtonAnimationRunning = !locationButtonAnimationRunning
        
        if locationButtonAnimationRunning {
            
            let array = [#imageLiteral(resourceName: "z_gps_realTime_RTLS_positioning_1"),#imageLiteral(resourceName: "z_gps_realTime_RTLS_positioning_2"),#imageLiteral(resourceName: "z_gps_realTime_RTLS_positioning_3"),#imageLiteral(resourceName: "z_gps_realTime_RTLS_positioning_4")]
            
            locationButton.imageView?.animationImages = array
            locationButton.imageView?.animationRepeatCount = 0
            locationButton.imageView?.animationDuration = 0.4
            locationButton.imageView?.startAnimating()
            
            
            NetworkCommand.putChatCommand(commandText: "GetPositionCellTower", serialNumber: nil, id: nil, clientType: nil, tokenPass: nil, success: { (response) in
                
                let putChatCommand = PutChatCommand.mj_object(withKeyValues: response)
                
                if putChatCommand != nil {
                    
                    if putChatCommand?.Status == "Success" {
                        
                        self.cancelTimerDate = Date.init()
                        
                        self.startTimer()
                        
                    }
                    
                }
                
            }, failure: { (Error) in
                
                self.locationButtonAnimationRunning = false
                
                self.locationButton.imageView?.stopAnimating()
                
            })
            
        }else {
            
            self.locationButtonAnimationRunning = false
            
            self.locationButton.imageView?.stopAnimating()
            
            stopTimer()
            
            
        }
        
        
        
    }
    
    // MARK: - 开启定时器
    func startTimer() {
        
        if locationButtonAnimationRunning {
            
            timer = nil
            
            timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(getNewPointInfo), userInfo: nil, repeats: true)
            
        }
        
        
    }
    
    // MARK: - 关闭定时器
    func stopTimer() {
        
        if timer != nil {
            
            timer?.invalidate()
            
            timer = nil
            
        }
        
    }
    
    // MARK: - 查看有无新上传点
    func getNewPointInfo() {
        
        let nowDate = Date.init()
        
        let marginTime = nowDate.timeIntervalSince(cancelTimerDate)
        
        if marginTime < 180 {
            
            if oneTimerFinish {
                
                oneTimerFinish = false
                
                NetworkCommand.getLastStatusData(listSerialNumber: nil, id: nil, clientType: nil, tokenPass: nil, success: { (response) in
                    
                    self.oneTimerFinish = true
                    
                    if UserModel.userModel.lastStatusDataArray != nil {
                        
                        if (UserModel.userModel.lastStatusDataArray?.count)! > 0 {
                            
                            for dict in UserModel.userModel.lastStatusDataArray! {
                                
                                let last = LastStatusData.mj_object(withKeyValues: dict)
                                
                                if last?.SerialNumber == UserModel.userModel.selectedDeviceSerialNumber {
                                    
                                    if (last?.GPSTime?.doubleValue)! > self.lastLocationTime.doubleValue {
                                        
                                        self.addCircle = true
                                        
                                        self.setUpInfoView()
                                        
                                        self.stopTimer()
                                        
                                        self.locationButtonAnimationRunning = false
                                        
                                        self.locationButton.imageView?.stopAnimating()
                                        
                                        
                                    }
                                    
                                }
                                
                            }
                            
                        }
                        
                    }
                    
                }, failure: { (Error) in
                    
                    self.oneTimerFinish = true
                    
                })
                
                
            }
            
        }else {
            
            self.stopTimer()
            
            self.locationButtonAnimationRunning = false
            
            self.locationButton.imageView?.stopAnimating()
            
            print(self.locationButton.state)
            
            SVProgressHUD.showError(withStatus: NSLocalizedString(LOCALIZABLE_STRING_FAILURE, comment: ""))
            
            SVProgressHUD.dismiss(withDelay: 1)
            
        }
        
        
        
        
    }

    
    // MARK: - 高德地图发起逆地理编码请求
    func searchReGeocodeWithCoordinate(coordinate: CLLocationCoordinate2D!) {
        
        let coor = AMapCoordinateConvert(coordinate, .GPS)
        
        let regeo: AMapReGeocodeSearchRequest = AMapReGeocodeSearchRequest()
        
        regeo.location = AMapGeoPoint.location(withLatitude: CGFloat(coor.latitude), longitude: CGFloat(coor.longitude))
        
        aMapSearcher.aMapReGoecodeSearch(regeo)
        
    }
    
    // MARK: - AMapSearchDelegate
    func aMapSearchRequest(_ request: Any!, didFailWithError error: Error!) {
        
        print("request :\(request), error: \(error)")
        
    }
    
    // MARK: - 高德地图逆地理查询回调
    func onReGeocodeSearchDone(_ request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) {
        
        //        print("response :\(response.formattedDescription())")
        
        print(response.regeocode.formattedAddress)
        
        if response.regeocode.formattedAddress != nil {
            
            self.locationInformationInfoLabel.text = response.regeocode.formattedAddress
            
        }
        
    }
    
    
    
    // MARK: - 百度地图反编码
    func baiduMapReverseGeoCode(coor:CLLocationCoordinate2D) {
        
        let baiduCoor = self.coorForWGS84ToBd09(coor: coor)
        
        let reverseGeoCodeOption:BMKReverseGeoCodeOption = BMKReverseGeoCodeOption.init()
        
        reverseGeoCodeOption.reverseGeoPoint = baiduCoor
        
        let flag:Bool = baiduMapSearcher.reverseGeoCode(reverseGeoCodeOption)
        
        if flag {
            
            
            
        }else {
            
            
            
        }
        
    }
    
    // MARK: - 获取百度地图反编码delegate结果
    func onGetReverseGeoCodeResult(_ searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
        
        if (error == BMK_SEARCH_NO_ERROR) {
            
            print(result.address)
            
            self.locationInformationInfoLabel.text = result.address
            
        }else {
            
            print("没有结果")
            
        }
        
    }
    
    // MARK: - 返回AnnotationView  delegate
    func mapView(_ mapView: BMKMapView!, viewFor annotation: BMKAnnotation!) -> BMKAnnotationView! {
        
        if annotation.isKind(of: BMKPointAnnotation.classForCoder()) {
            
            let newAnnotaitonView = BMKAnnotationView.init(annotation: annotation, reuseIdentifier: "myAnnotation")
            
            if isBaseStation {
                newAnnotaitonView?.image = #imageLiteral(resourceName: "z_gps_realTime_GPS")
            }else {
                newAnnotaitonView?.image = #imageLiteral(resourceName: "z_gps_box_jizhan")
            }
            
            newAnnotaitonView?.centerOffset = CGPoint.init(x: 0, y: -((newAnnotaitonView?.frame.size.height)! / 2))
            
            return newAnnotaitonView
            
        }
        
        return nil
        
    }
    
    
    func mapView(_ mapView: BMKMapView!, viewFor overlay: BMKOverlay!) -> BMKOverlayView! {
        
        if overlay.isKind(of: BMKCircle.classForCoder()) {
            
            let circleView = BMKCircleView.init(overlay: overlay)
            
            circleView?.fillColor = UIColor.red.withAlphaComponent(0.4)
            //
            //            circleView?.strokeColor = UIColor.red.withAlphaComponent(0.4)
            //
            //            circleView?.lineWidth = 8.0
            
            return circleView
            
        }
        
        return nil
        
    }
    
    // MARK: - 转换百度坐标
    func coorForWGS84ToBd09(coor:CLLocationCoordinate2D) -> CLLocationCoordinate2D {
        
        //转换WGS84坐标至百度坐标(加密后的坐标)
        let testdic = BMKConvertBaiduCoorFrom(coor, BMK_COORDTYPE_GPS)
        
        //        print(testdic!)
        
        //解密加密后的坐标字典
        let baiduCoor = BMKCoorDictionaryDecode(testdic)//转换后的百度坐标
        
        return baiduCoor
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

class GPSLocationViewControllerForAMap: NSObject,MAMapViewDelegate {
    
    var isBaseStation = false
    
    // MARK: - annotationView代理
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        
        if annotation.isKind(of: MAPointAnnotation.classForCoder()) {
            
            let newAnnotaitonView = MAAnnotationView.init(annotation: annotation, reuseIdentifier: "myAnnotation")
            
            if isBaseStation {
                newAnnotaitonView?.image = #imageLiteral(resourceName: "z_gps_realTime_GPS")
            }else {
                newAnnotaitonView?.image = #imageLiteral(resourceName: "z_gps_box_jizhan")
            }
            
            newAnnotaitonView?.centerOffset = CGPoint.init(x: 0, y: -((newAnnotaitonView?.frame.size.height)! / 2))
            
            return newAnnotaitonView
            
        }
        
        return nil
        
    }
    
    // MARK: - 画圈
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        if overlay.isKind(of: MACircle.self) {
            let renderer: MACircleRenderer = MACircleRenderer(overlay: overlay)
//            renderer.lineWidth = 8.0
//            renderer.strokeColor = UIColor.red
            renderer.fillColor = UIColor.red.withAlphaComponent(0.4)
            
            return renderer
        }
        return nil
    }
    
}
